<template>
  <div class="main-box">
    <el-page-header
      :title="$t('title.back')"
      @back="goBack"
      :content="$t('title.detailApp')"
    > </el-page-header>
    <el-row class="pull-right">
      <el-button
        v-has="'ams:platformApp:publish'"
        :size="size"
        type="primary"
        @click="dialogPublish.visible = true"
      >{{
        $t('btnText.publish')
      }}</el-button>
      <el-button
        v-has="'ams:platformApp:upgrade'"
        :size="size"
        type="primary"
        plain
        @click="dialogUpgrade.visible = true"
      >{{
        $t('btnText.upgrade')
      }}</el-button>
      <el-button
        v-has="'ams:platformApp:clone'"
        :size="size"
        type="primary"
        plain
        @click="toClone"
      >{{ $t('btnText.clone') }}</el-button>
      <el-button
        v-has="'ams:platformApp:edit'"
        :size="size"
        type="primary"
        plain
        @click="toEdit"
      >{{ $t('btnText.edit') }}</el-button>
      <el-button
        v-has="'ams:platformApp:delete'"
        :size="size"
        type="danger"
        plain
        v-if="status === 1 || status === 3"
        @click="toDelete"
      >{{
        $t('btnText.delete')
      }}</el-button>
      <el-button
        v-has="'ams:platformApp:offline'"
        :size="size"
        type="danger"
        plain
        v-if="status === 2"
        @click="toOffline"
      >{{
        $t('btnText.offline')
      }}</el-button>
    </el-row>
    <div class="content-box">
      <el-tabs
        type="border-card"
        ref="tabs"
      >
        <el-tab-pane :label="$t('label.basicInfo')">
          <BasicInfo :formdata="formData"></BasicInfo>
        </el-tab-pane>
        <el-tab-pane :label="$t('label.publishRecords')">
          <PublishRecords
            :formdata="formData"
            :updateTime="updateTime"
          ></PublishRecords>
        </el-tab-pane>
        <el-tab-pane :label="$t('label.upgradeRecords')">
          <UpgradeRecords
            :formdata="formData"
            :updateTime="updateTime"
          ></UpgradeRecords>
        </el-tab-pane>
        <el-tab-pane :label="$t('label.authList')">
          <AuthList
            :formdata="formData"
            :updateTime="updateTime"
          ></AuthList>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 发布应用窗口 -->
    <el-dialog
      :title="$t('dialog.publishApp.title')"
      :visible.sync="dialogPublish.visible"
      width="600px"
      :close-on-click-modal="dialogPublish.closeOnClickModal"
      :close-on-press-escape="dialogPublish.closeOnPressEscape"
      append-to-body
      element-loading-background="rgba(0, 0, 0, 0.5)"
      @close="closedialogPublish"
    >
      <el-form
        :model="dialogPublish.formData"
        :rules="rulesPublish"
        ref="publishApp"
        label-width="100px"
        :size="size"
      >
        <el-form-item
          :label="$t('label.publishTo')"
          prop="type"
        >
          <el-radio-group v-model="dialogPublish.formData.type">
            <el-radio
              v-for="(item, index) in publishType"
              :key="index"
              :label="item.value"
            >{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label=""
          prop="publishTo"
          v-if="dialogPublish.formData.type === 2 || dialogPublish.formData.type === '2'"
        >
          <el-select
            v-model="dialogPublish.formData.publishTo"
            :placeholder="$t('placeholder.publishTo')"
            filterable
            multiple
          >
            <el-option
              v-for="item in customers"
              :key="item.id"
              :value="item.id"
              :label="item.customer"
            ><span>{{ item.customer }}</span><span class="sub-right">ID: {{ item.id }}</span></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          :label="$t('label.indate')"
          prop="indate"
        >
          <el-date-picker
            type="date"
            :placeholder="$t('placeholder.indate')"
            v-model="dialogPublish.formData.indate"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          :size="size"
          @click="dialogPublish.visible = false"
        >{{ $t('btnText.cancel') }}</el-button>
        <el-button
          :size="size"
          type="primary"
          @click="submitPublish('publishApp')"
        >{{ $t('btnText.ok') }}</el-button>
      </span>
    </el-dialog>
    <!-- 版本升级窗口 -->
    <el-dialog
      :title="$t('dialog.upgradeApp.title')"
      :visible.sync="dialogUpgrade.visible"
      width="920px"
      :close-on-click-modal="dialogUpgrade.closeOnClickModal"
      :close-on-press-escape="dialogUpgrade.closeOnPressEscape"
      append-to-body
      element-loading-background="rgba(0, 0, 0, 0.5)"
    >
      <el-form
        :model="dialogUpgrade.formData"
        :rules="rulesUpgrade"
        ref="upgradeApp"
        label-width="120px"
        :size="size"
      >
        <el-form-item
          :label="$t('label.version')"
          prop="version"
        >
          <el-input
            :size="size"
            v-model="dialogUpgrade.formData.version"
            :placeholder="$t('placeholder.version')"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          :label="$t('label.urlPc')"
          prop="urlPc"
          v-if="formData.platformType === 1 || formData.platformType === 2"
        >
          <el-input
            :size="size"
            v-model="dialogUpgrade.formData.urlPc"
            :placeholder="$t('placeholder.urlPc')"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          :label="$t('label.urlApp')"
          prop="urlApp"
          v-if="formData.platformType === 1 || formData.platformType === 3"
        >
          <el-input
            :size="size"
            v-model="dialogUpgrade.formData.urlApp"
            :placeholder="$t('placeholder.urlApp')"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          :label="$t('label.meteringJson')"
          prop="meteringJson"
        >
          <el-input
            :size="size"
            v-model="dialogUpgrade.formData.meteringJson"
            type="textarea"
            :placeholder="$t('placeholder.meteringJson')"
            autocomplete="off"
            style="display: none"
          ></el-input>
          <vue-json-editor
            v-model="jsonObj"
            :showBtns="false"
            :mode="'code'"
          />
        </el-form-item>
        <el-form-item
          :label="$t('label.upgradeExplain')"
          prop="upgradeExplain"
        >
          <el-input
            :size="size"
            class="row80"
            v-model="dialogUpgrade.formData.upgradeExplain"
            type="textarea"
            :placeholder="$t('placeholder.upgradeExplain')"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          :size="size"
          @click="dialogUpgrade.visible = false"
        >{{ $t('btnText.cancel') }}</el-button>
        <el-button
          :size="size"
          type="primary"
          @click="submitUpgrade('upgradeApp')"
        >{{ $t('btnText.ok') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  appUpgrade,
  getAppDetail,
  appDelete,
  appPublish,
  appOffline,
  getUserInfo,
  getCustomerList
} from '../../api/api';
import { errorCode } from '@/utils/index';
import BasicInfo from './basicInfo.vue';
import PublishRecords from './publishRecords.vue';
import UpgradeRecords from './upgradeRecords.vue';
import AuthList from './authList.vue';
import vueJsonEditor from 'vue-json-editor';
export default {
  name: 'detail',
  props: {
    target: {
      type: Number,
      default: 0
    }
  },
  components: {
    vueJsonEditor,
    BasicInfo,
    PublishRecords,
    UpgradeRecords,
    AuthList
  },
  data() {
    return {
      size: 'medium',
      customers: [],
      jsonObj: {},
      updateTime: 0,
      status: 0,
      showPublishRecords: false,
      formData: {
        chName: '',
        description: '',
        enName: '',
        icon: '',
        iconColor: '',
        meteringJson: '',
        operator: '',
        platformType: 0,
        typeId: '',
        type: '',
        status: 0,
        urlApp: '',
        urlPc: '',
        version: '',
        updatedBy: '',
        updatedAt: ''
      },
      dialogPublish: {
        visible: false,
        closeOnClickModal: false,
        closeOnPressEscape: false,
        formData: {
          type: 1,
          indate: '',
          operator: '',
          publishTo: [0]
        }
      },
      dialogUpgrade: {
        visible: false,
        closeOnClickModal: false,
        closeOnPressEscape: false,
        formData: {
          id: 0,
          meteringJson: '',
          operator: '',
          upgradeExplain: '',
          urlApp: '',
          urlPc: '',
          version: ''
        }
      }
    };
  },
  computed: {
    publishType() {
      return [
        { value: 1, label: this.$t('publishType[1]') },
        { value: 2, label: this.$t('publishType[2]') }
      ];
    },
    rulesPublish() {
      return {
        type: [{ required: true, trigger: 'change', message: ' ' }],
        publishTo: [{ type: 'array', required: true, message: this.$t('error.publishTo'), trigger: ['blur', 'change'] }]
      };
    },
    rulesUpgrade() {
      return {
        version: [
          { required: true, trigger: 'blur', message: this.$t('error.version') },
          { validator: this.validateVersion, trigger: 'blur', message: this.$t('error.version') }
        ],
        urlPc: [{ required: true, trigger: 'blur', message: this.$t('error.urlPc') }],
        urlApp: [{ required: true, trigger: 'blur', message: this.$t('error.urlApp') }],
        meteringJson: [{ validator: this.validateJson, trigger: 'blur', message: this.$t('error.meteringJson') }]
      };
    },
    iconColor() {
      return `color: ` + this.formData.iconColor;
    }
  },
  watch: {
    'dialogPublish.formData.type'(val) {
      if (val === 1) {
        this.dialogPublish.formData.publishTo = [0];
      } else {
        this.dialogPublish.formData.publishTo = [];
      }
    },
    jsonObj: {
      handler(n, o) {
        if (n) {
          this.$nextTick(() => {
            console.info(n);
            this.dialogUpgrade.formData.meteringJson = JSON.stringify(n);
          });
        }
      },
      immediate: true
    }
  },
  created() {
    this.getUserInfo();
    this.getCustomers();
    this.getAppDetail();
  },
  methods: {
    validateVersion(rule, value, callback) {
      let myreg = /^[a-zA-Z0-9.]{2,10}$/;
      if (!myreg.test(value)) {
        callback(new Error(this.$t('error.version')));
      }
      callback();
    },
    validateJson(rule, value, callback) {
      if (value === '') {
        callback();
      } else {
        try {
          let obj = JSON.parse(value);
          if (typeof obj === 'object' && obj) {
            callback();
          } else {
            callback(new Error(this.$t('error.meteringJson')));
          }
        } catch (e) {
          callback(new Error(this.$t('error.meteringJson')));
        }
      }
    },
    updateTimetoChange() {
      this.updateTime = new Date().getTime();
    },
    goBack() {
      this.$emit('toChangeComponentName', 'list');
    },
    toClone() {
      this.$emit('toChangeComponentName', 'add');
    },
    toEdit() {
      this.$emit('toChangeComponentName', 'edit');
    },
    toDelete() {
      this.$confirm(this.$t('warning.deleteApp'), this.$t('warning.title'), {
        type: 'warning',
        confirmButtonText: this.$t('btnText.ok'),
        cancelButtonText: this.$t('btnText.cancel')
      })
        .then(() => {
          appDelete({ id: this.formData.id }).then(res => {
            this.$message.success(errorCode(res.message));
            this.goBack();
          });
        })
        .catch(() => {});
    },
    toOffline() {
      this.$confirm(
        '<div class="dangerIcon"></div><div class="align-center">' + this.$t('warning.offlineApp') + '</div>',
        this.$t('title.offlineApp'),
        {
          dangerouslyUseHTMLString: true,
          confirmButtonText: this.$t('btnText.ok'),
          cancelButtonText: this.$t('btnText.cancel')
        }
      )
        .then(() => {
          appOffline({
            id: this.formData.id,
            operator: this.dialogPublish.formData.operator,
            version: this.formData.version
          }).then(res => {
            this.$message.success(errorCode(res.message));
            this.getAppDetail();
          });
        })
        .catch(() => {});
    },
    getUserInfo() {
      getUserInfo().then(res => {
        this.dialogPublish.formData.operator = res.data.name;
        this.dialogUpgrade.formData.operator = res.data.name;
      });
    },
    getCustomers() {
      getCustomerList().then(res => {
        this.customers = res.data;
      });
    },
    getAppDetail() {
      this.formData.id = this.target;
      getAppDetail({ id: this.target }).then(res => {
        this.status = res.data.status;
        for (let p in res.data) {
          this.formData[p] = res.data[p];
          this.dialogUpgrade.formData[p] = res.data[p];
        }
        if (this.formData.status !== 1) {
          this.showPublishRecords = true;
        }
        this.updateTimetoChange();

        if (this.formData.status === 1) {
          this.$nextTick(() => {
            this.$refs.tabs.$children[0].$refs.tabs[1].style.display = 'none';
          });
        }
        try {
          let obj = JSON.parse(this.formData.meteringJson);
          if (typeof obj === 'object' && obj) {
            this.jsonObj = obj;
          } else {
            this.jsonObj = {};
          }
        } catch (e) {
          this.jsonObj = {};
        }
      });
    },
    submitPublish(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let formData = {
            id: this.target,
            operator: this.dialogPublish.formData.operator,
            indate: this.dialogPublish.formData.indate,
            version: this.formData.version,
            publishTo: []
          };
          let publishTo = this.dialogPublish.formData.publishTo;
          if (publishTo.length === 1 && publishTo[0] === 0) {
            formData.publishTo.push({ id: 0, name: '所有人' });
          } else {
            for (let item of publishTo) {
              for (let i of this.customers) {
                if (i.id === item) {
                  formData.publishTo.push({ id: i.id, name: i.customer });
                }
              }
            }
          }
          appPublish(formData).then(res => {
            this.$message.success(errorCode(res.message));
            this.dialogPublish.visible = false;
            this.getAppDetail();
          });
          return false;
        }
      });
    },
    submitUpgrade(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          appUpgrade(this.dialogUpgrade.formData).then(res => {
            this.$message.success(errorCode(res.message));
            this.dialogUpgrade.visible = false;
            this.getAppDetail();
          });
          return false;
        }
      });
    },
    closedialogPublish() {
      this.$refs['rulesPublish'].resetFields();
    }
  }
};
</script>

<style>
.el-tabs--border-card {
  border: none !important;
}
.align-center {
  text-align: center;
}
.dangerIcon {
  height: 55px;
  background-image: url('../../assets/danger.png');
  background-repeat: no-repeat;
  background-position: center;
  margin-bottom: 10px;
}
</style>
<style lang="scss" scoped>
.main-box {
  position: relative;
  color: #606266;
  height: 100%;
  background-color: #ffffff;
}
.content-box {
  height: calc(100% - 57px);
  overflow: hidden;
}
.el-select,
.el-input {
  width: 100% !important;
}
.el-page-header {
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
}
.pull-right {
  position: absolute;
  top: 10px;
  right: 20px;
}
.sub-right {
  float: right;
  color: #909399;
  font-weight: normal;
  margin-right: 30px;
}
::v-deep .el-textarea__inner {
  height: 200px;
  resize: none;
}
.row80 ::v-deep .el-textarea__inner {
  height: 80px;
  resize: none;
}
.el-tabs {
  height: 100%;
}
.el-tab-pane {
  height: 100%;
}
::v-deep .el-tabs__item {
  padding: 0 30px;
  height: 48px;
  line-height: 48px;
  font-size: 16px;
}
::v-deep .el-tabs__content {
  height: calc(100% - 47px);
  overflow: auto;
  padding: 20px !important;
  position: relative;
}
</style>
